package com.atguigu.realtime.utils

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent

import scala.collection.mutable

/**
 * Created by Smexy on 2022/8/26
 */
object DStreamUtil {

  def getDStream(context:StreamingContext,groupId:String,topic:String,
                 ifSaveOffsetsToMysql:Boolean=false,
                 offsets:mutable.Map[TopicPartition, Long]=null):InputDStream[ConsumerRecord[String, String]]={


    val kafkaParams = Map[String, Object](
      //引入模块中提供的工具类是可以直接使用的
      "bootstrap.servers" -> PropertiesUtil.getValue("kafka.broker.list"),
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> groupId,
      "auto.offset.reset" -> "earliest",
      //如果要实现精确一次，必须在at least once的基础上实现，at least once必须要求取消自动提交
      "enable.auto.commit" -> "false"
    )


    val topics = Array(topic)

  if (ifSaveOffsetsToMysql){

    //如果要实现事务输出，需要从Mysql中维护的offsets获取流
    KafkaUtils.createDirectStream[String, String](
      context,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams,offsets)
    )


  }else{
    //根据偏移量存储位置的不同，返回不同的ds
    KafkaUtils.createDirectStream[String, String](
      context,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )
  }


  }

}
